//
//  TopicViewController.m
//  BobNews
//
//  Created by lanou3g on 16/5/6.
//  Copyright © 2016年 YJC. All rights reserved.
//

#import "TopicViewController.h"
#import "HeadImageModelCell.h"
#import "MulImageModelCell.h"
#import "NetWorkRequestManager.h"
#import "BaseModel.h"
#import "BaseModelCell.h"
#import "TopicListController.h"
#import "LORefresh.h"
@interface TopicViewController ()<UISearchDisplayDelegate,UISearchBarDelegate>
@property (nonatomic,strong) NSMutableArray *topicArray;

@property (nonatomic,strong) NSMutableArray *data;
@property (nonatomic,strong) NSMutableArray *filterData;
@property (nonatomic,strong)UISearchDisplayController *searchDisplayController;

@end

@implementation TopicViewController
- (void)dealloc {
    [self.tableView removeObserver:[self.tableView defaultHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.topicArray = [NSMutableArray new];
//    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"back7.jpeg"]];
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,44)];
    searchBar.placeholder = @"搜索";
    // 添加 searchbar 到 headerview
    self.tableView.tableHeaderView = searchBar;
    self.searchDisplayController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
    self.searchDisplayController.searchResultsDataSource = self;
    self.searchDisplayController.searchResultsDelegate = self;

    
    self.navigationItem.title = @"话题";
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"HeadImageModelCell" bundle:nil] forCellReuseIdentifier:@"HeadImageModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"MulImageModelCell" bundle:nil] forCellReuseIdentifier:@"MulImageViewModel"];
    [self loadData];
    
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.topicArray removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf loadData];
    }];
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        [weakSelf loadData];
    }];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (void)loadData {
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:@"http://topic.comment.163.com/topic/list/subject/0-40.html"] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dataDict = jsonDict[@"data"];
            NSArray *subjectlistArray = dataDict[@"subjectList"];
            for (NSDictionary *itemDict in subjectlistArray) {
                BaseModel *model = [BaseModel modelWithDictionary:itemDict];
                [self.topicArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [[self.tableView defaultHeader]endRefreshing];
                [[self.tableView defaultFooter]endRefreshing];
            });
        }
        
    }];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    if (tableView == self.tableView) {
        return self.topicArray.count;
    }else{
        BaseModel *model = [[BaseModel alloc]init];
        // 谓词搜索
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self contains [cd] %@",self.searchDisplayController.searchBar.text];
        self.filterData =  [[NSMutableArray alloc] initWithArray:[self.data filteredArrayUsingPredicate:predicate]];
        return self.filterData.count;
    }

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [BaseModelCell cellWithTableView:tableView Model:self.topicArray[indexPath.row] indexPath:indexPath];
    if (cell == nil) {
        cell = [BaseModelCell cellWithTableView:tableView Model:self.topicArray[indexPath.row] indexPath:indexPath];
    }
    if (tableView == self.tableView) {
        cell.textLabel.text = _data[indexPath.row];
    }else{
        cell.textLabel.text = _filterData[indexPath.row];
    }
    // Configure the cell...
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 230;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    TopicListController *topicListVC = [[TopicListController alloc]init];
    topicListVC.navTitle = [self.topicArray[indexPath.row] name];
    topicListVC.subjectId = [self.topicArray[indexPath.row] subjectId];
    topicListVC.talkId = [self.topicArray[indexPath.row] talkId];
    topicListVC.model = self.topicArray[indexPath.row];
    [self.navigationController pushViewController:topicListVC animated:YES];
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
